#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <search.h>
#include "gameserver.h"
#include "workthread.h"
#include "hashtable.h"
#include "list.h"
#include "functions.h"
#include "utils.h"

typedef void(*func)(request_t*);
static hashtable_t *funtable;

list_t * requestlist;
pthread_mutex_t requestlistlock;
pthread_t * workthread_pid;


inline void registercmd(char * cmdcode,func * function){
	printf("register command %s\n",cmdcode);
	hash_insert(cmdcode,function,funtable);
}

void initthreads(int threadcount){
	funtable=create_hashtable(100);

	requestlist=list_create();
	pthread_mutex_init(&requestlistlock,PTHREAD_MUTEX_TIMED_NP);
	init();
	//////////////////////////////////////////////////////////////////////////

	registercmd("login",(func *)do_login);
	registercmd("creategame",(func *)do_creategame);
	registercmd("joingame",(func *)do_joingame);
	registercmd("ready",(func *)do_ready);
	registercmd("gamemsg",(func *)do_gamemsg);
	registercmd("fetchgamelist",(func *)do_fetchgamelist);
	registercmd("gameuser",(func *)do_gameuser);

















	//////////////////////////////////////////////////////////////////////////

	//create pthread
	workthread_pid=malloc(sizeof(pthread_t) * threadcount);

	int i;
	for(i=0;i<threadcount;i++){
		pthread_create((workthread_pid+i), NULL, workthread, NULL);
	}

}



void * workthread(void *arg){

	for(;;){
		pthread_mutex_lock(&requestlistlock);
		request_t *prequest=list_pop_head(requestlist);
		pthread_mutex_unlock(&requestlistlock);
		if(prequest!=NULL){

			do_request(prequest);
			free(prequest->querystring);
			free(prequest);
		}else{
			usleep(20);
		}
	}
}

void do_request(request_t* pRequest) {
	char cmd[25]={0};

	getparam(cmd,sizeof(cmd)-1,0,0,pRequest->querystring);
	strlwr(cmd);
	printf("cmd:%s\n",cmd);
	func fun=hash_value(cmd,funtable);
	if(fun){
		fun(pRequest);
	}

}
